# coding: utf-8
#文件操作

import struct
import shutil
import hashlib
import SHA256_op
import RSA_op

#将数据以十六进制写入文件
def write_file(filename, num):
    f = open(filename,'wb')
    hex_str = hex(num)[2:]
    if len(hex_str)%2 != 0:  #奇数在前补0，防止出错
        hex_str = '0'+hex_str
    strY = ''
    i = 0
    for x in hex_str :   #逐个字符迭代
        if x != ' ' and x!= '\n' and x!= '\r' and x!= '\t': #过滤掉空格、回车(换行）、制表符
            strY += x    #将字符串连接到strY
            i+=1
            if(i%2 == 0):     #每两个字符转换一次为HEX，并写入文件
                xHex = int(strY,16)   #将两个字符转为HEX “ff ”->0x000000ff
                xHex = struct.pack("B",xHex)   #将HEX数据转为unsigned char的字符串
                f.write(xHex)   #write()函数参数只能为str类型
                strY = ''  #strY 置为空字符串
    f.close()

#读文件操作
#读取文件到十进制数字（用于RSA加密和解密）
def read_file_dec(filename):
    f = open(filename,'rb')
    s = f.read(1)
    file = 0
    while s:
        file *= 256
        byte = ord(s)
        file += byte
        s = f.read(1)
    return file

#读取文件为十六进制字符串，用于填写证书里的公钥字段
def read_file_hex(filename):
    f = open(filename,'rb')
    s = f.read(1)
    file = ''
    while s:
            byte = hex(ord(s))[2:]
            if len(byte)==1:
                file += '0'
            file += byte
            s = f.read(1)
    return file.upper()

#写入序列号(申请文件的SHA256值)
def write_id(username):
    #username = input("请输入用户名:")
    ca_num = SHA256_op.cal_file_sha256(username+'_CA.csr')
    with open(username+'_CA.csr',"a+") as f:
       f.write("user id:"+ca_num+'\n')
    print("追加写入序列号完成")

#显示SHA256的值
def show_sha256():
    username = input("请输入用户名:")
    ca_num = SHA256_op.cal_file_sha256(username+'_CA.csr')
    print(int(ca_num,16))

#复制文件
def copy_file(username):
    #username = input("请输入用户名:")
    shutil.copy(username+'_apply.csr', username+'_CA.csr')
    print("复制成功")

#生成密钥文件
def create_key_file(username):
    #print(username)
    public_key, private_key = RSA_op.gen_key()
    #username = input("请输入用户名:")
    public_name = username + "_public.key"
    private_name = username + "_private.key"
    write_file(public_name, public_key)
    #print("公钥文件已生成")
    write_file(private_name, private_key)
    #print("私钥文件已生成")
    return 1